<template>
  <s-layout>
    <view class="container">
      <!-- Header Section -->
      <view class="header-box">
        <text
          class="cicon-key"
          style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
        ></text>
        <text class="title">更改个人信息</text>
      </view>

      <!-- Avatar Section -->
      <!-- This card uses standard elements, keeping its structure -->
      <view class="form-card avatar-section" @tap="chooseAvatar">
        <text class="label">头像</text>
        <view class="avatar-right">
          <image class="avatar-img" :src="displayAvatarUrl" mode="aspectFill" />
          <image
            class="arrow-icon"
            src="@/static/tabs/更多.png"
            mode="scaleToFill"
          />
        </view>
      </view>

      <!-- Submit Button -->
      <view class="submit-btn-container">
        <view class="submit-btn" @click="saveChanges">
          <text class="btn-text">确认修改</text>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import { s } from "@/dist/dev/mp-weixin/common/vendor";
// Removed unused dayjs import

// --- State ---
const formData = reactive({
  name: "",
  phone: "",
});

// Holds the URL to display (can be existing URL or temporary local path)
const displayAvatarUrl = ref("");
// Holds the *new* avatar path returned from the server after upload
const newAvatarServerPath = ref<string | null>(null);

// Get current user info from store or API
const userInfo = sheep.$store("user").userInfo; // Assuming store has user info like { ur_name, wx_user, ur_phone, wx_avatarUrl }

// --- Lifecycle Hooks ---
onLoad(async () => {
  uni.showLoading({ title: "加载中..." });
  try {
    // Assuming userInfo is populated in the store after login
    if (userInfo) {
      // Map relevant fields to formData
      formData.name = userInfo.ur_name || ""; // Adjust 'ur_name' if needed
      formData.phone = userInfo.ur_phone || ""; // Adjust 'ur_phone' if needed

      // Set initial display avatar
      displayAvatarUrl.value =
        userInfo.wx_avatarUrl 
    } else {
      console.error("User info not found in store.");
      uni.showToast({ title: "请先登录", icon: "none" });
      // Potentially redirect
    }
  } catch (error) {
    console.error("Error loading user data:", error);
    uni.showToast({ title: "加载数据出错", icon: "none" });
  } finally {
    uni.hideLoading();
  }
});

// --- Methods ---

// Choose and Upload Avatar
const chooseAvatar = async () => {
  try {
    const chooseRes = await uni.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
    });

    const tempFilePath = chooseRes.tempFilePaths[0];
    displayAvatarUrl.value = tempFilePath;
    newAvatarServerPath.value = null;

    uni.showLoading({ title: "上传头像中..." });

    const upLoadrUrl =
      "https://assess.yuejin-tech.com/app_api.php?t=upload&op=image_upload&role=company&type=avatarUrl";
    const token = sheep.$store("user").getToken
      ? sheep.$store("user").getToken()
      : null;
    const headers: Record<string, any> = {};
    if (token) {
      headers["Authorization"] = "Bearer " + token; // Adjust header as needed
    }

    uni.uploadFile({
      url: upLoadrUrl,
      filePath: tempFilePath,
      name: "file",
      header: headers,
      success: (uploadFileRes) => {
        console.log("Upload success raw response:", uploadFileRes);
        try {
          const res = JSON.parse(
            uploadFileRes.data.replace(/\ufeff/g, "") || "{}"
          );
          console.log("Parsed server response:", res);

          if (res.data) {
            const relativePath = res.data;
            const serverUrl = relativePath;

            console.log("上传成功，服务器URL:", serverUrl);
            newAvatarServerPath.value = serverUrl;

            uni.hideLoading();
            uni.showToast({
              title: "头像上传成功",
              icon: "success",
              duration: 1500,
            });
          } else {
            const errorMessage = res.msg || res.message || "头像上传失败";
            console.error("头像上传失败 (API Error):", errorMessage, res);
            uni.hideLoading();
            uni.showToast({ title: errorMessage, icon: "none" });
            displayAvatarUrl.value =
              userInfo?.wx_avatarUrl ;
            newAvatarServerPath.value = null;
          }
        } catch (parseError) {
          console.error("解析服务器响应失败:", parseError, uploadFileRes.data);
          uni.hideLoading();
          uni.showToast({ title: "处理服务器响应失败", icon: "none" });
          displayAvatarUrl.value =
            userInfo?.wx_avatarUrl ;
          newAvatarServerPath.value = null;
        }
      },
      fail: (err) => {
        console.error("头像上传失败 (uni.uploadFile):", err);
        uni.hideLoading();
        uni.showToast({ title: "头像上传网络错误", icon: "none" });
        displayAvatarUrl.value =
          userInfo?.wx_avatarUrl ;
        newAvatarServerPath.value = null;
      },
    });
  } catch (chooseError: any) {
    if (chooseError.errMsg && chooseError.errMsg.includes("cancel")) {
      console.log("用户取消选择头像");
    } else {
      console.error("选择头像时发生错误:", chooseError);
      uni.showToast({ title: "选择图片失败", icon: "none" });
    }
    uni.hideLoading();
  }
};

// Validate Phone (Simple Example)
const isValidPhone = (phone: string): boolean => {
  // Basic check for 11 digits, refine if needed (e.g., starting with '1')
  const phoneRegex = /^\d{11}$/;
  return phoneRegex.test(phone);
};

// Save Changes
const saveChanges = async () => {
  uni.showLoading({ title: "正在保存...", mask: true });

  const payload: Record<string, any> = {
    // Adjust keys (e.g., 'name' to 'ur_name') if your API expects different field names
    wx_avatarUrl: newAvatarServerPath.value.replace(/^https?:\/\/[^\/]+/, ""),
    wx_id: sheep.$store("user").userInfo.wx_id,
  };

  // Include avatar URL only if a new one was uploaded
  if (newAvatarServerPath.value) {
    // Adjust key 'avatar' to match API (e.g., 'wx_avatarUrl', 'avatar_url')
    payload.avatar = newAvatarServerPath.value.replace(/^https?:\/\/[^\/]+/, "");;
  }

  try {
    // Ensure sheep.$api.user.edit exists and accepts the payload structure
    const response = await sheep.$api.qy_index.userEdit(payload);

    uni.hideLoading();

    if (response.code === 200) {
      // Adjust success code if necessary
      uni.showToast({
        title: "修改成功",
        icon: "success",
        duration: 1500,
      });

      // Update user info in the store
      const updatedUserInfo = { ...sheep.$store("user").userInfo };
      updatedUserInfo.ur_name = formData.name; // Adjust store field name
      updatedUserInfo.ur_phone = formData.phone; // Adjust store field name
      updatedUserInfo.wx_avatarUrl = displayAvatarUrl.value; // Adjust store field name

      if (sheep.$store("user").updateUserInfo) {
        sheep.$store("user").updateUserInfo(updatedUserInfo);
      } else {
        console.warn(
          "Store action 'updateUserInfo' not found. Updating local ref."
        );
        Object.assign(sheep.$store("user").userInfo, updatedUserInfo); // Fallback update
      }

      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: response.msg || "保存失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("Save changes error:", error);
    uni.showToast({
      title: "网络错误或服务异常",
      icon: "none",
      duration: 2000,
    });
  }
};
</script>

<style lang="scss" scoped>
/* Import icon fonts if not globally available */
/* @import "/src/sheep/scss/icon/_cicon.scss"; */ /* Example path */

.container {
  padding: 20rpx 30rpx 120rpx 30rpx; /* Keep bottom padding for fixed button */
  background: #f8f9fa;
  min-height: 100vh; /* Ensure background covers full height */
  box-sizing: border-box;
}

/* Header styles - Keep as is */
.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

/* General Form Card Style */
.form-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 0 20rpx; /* Horizontal padding handled by card */
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.05);
}

/* Avatar Section Styles - Keep specific styles */
.avatar-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 140rpx;
  padding: 20rpx; /* Add vertical padding */
  box-sizing: border-box;

  .label {
    font-size: 33rpx; /* Slightly larger label */
    color: #333;
    font-weight: 500;
  }
  .avatar-right {
    display: flex;
    align-items: center;
  }
  .avatar-img {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    border: 1px solid #eee;
    margin-right: 15rpx;
  }
  .arrow-icon {
    width: 25rpx;
    height: 25rpx;
    opacity: 0.6;
  }
}

/* Info Card Styles - Applying pattern from working example */
.info-card {
  padding: 20rpx 20rpx 0 20rpx; // Add top/horizontal padding like working example

  // Target fui-input within this specific card
  ::v-deep .fui-input__wrap {
    padding-left: 0 !important; // Remove wrapper padding
    padding-right: 0 !important;
  }
  ::v-deep .fui-input__padding {
    padding: 26rpx 0 !important; // Set consistent internal padding for input area
  }
  // Ensure border props on fui-input components control the visual lines
}

// Submit Button Styling (Fixed at bottom) - Keep as is
.submit-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom));
  background-color: #f8f9fa; // Or #fff
  z-index: 10;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05); // Optional top shadow
}

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 82, 217, 0.3);
  transition: background 0.3s ease;

  &:active {
    background: linear-gradient(
      135deg,
      darken(#0052d9, 5%),
      darken(#2979ff, 5%)
    );
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
  }
}
</style>
